define(['qiniu','pub','dragsortS','viewer'] ,function(qiniu){
    var  up7niuKey = '';
    var thumbTypeIcons = ['mp4','pdf'];
    var back = {
        o: {},
        upload7Opt: {
            key: '',
            baseUrl: '',
        },
        init: function (opt){
            var me = this;
            var o = $.extend({
                namespace: 'up7',
                areaCls: 'area',// area cls
                btnCls: 'btn', // 上传按钮 cls
                tipCls: 'tip', // tip说明 cls
                thumbCls: 'thumb', // thumb容器 cls
                fileCls: 'upfiler', //input file cls
                tokenUrl: base + '/ui/amms/integralTask/getToken', //请求token url
                hen: '_',
                opt: {
                    accept: 'image/jpeg,image/png,video/mp4',
                    multiple: true,
                    maxSize: '2M',
                    btnTxt: '上传有效文件',
                    tipTxt: '支持格式:JPG\\PNG\\mp4',
                    input: '.txt-proPic',
                    path: '',
                    data: null,
                },
            }, opt || {});

            o.$area = $('.' + o.namespace + o.hen + o.areaCls);
            o._btn = o.namespace + o.hen + o.btnCls;
            o._tip = o.namespace + o.hen + o.tipCls;
            o._thumb = o.namespace + o.hen + o.thumbCls;
            o._file = o.namespace + o.hen + o.fileCls;

            this.o = o;
            this.upload7Opt = window.upload7Opt;
            this.getUpKey();
            o.$area.each(function (i, v){
                me.getSelfOpts($(v));
                me.htmlInit($(v)); // 插入 input file 用作上传
                me.upload($(v)); // 上传
            });

        },
        getUpKey: function(){ // 获取 七牛 token
            var me = this;
            if(!up7niuKey){
                $ajax.post({
                    url: me.o.tokenUrl,
                    callback: function (rst){
                        console.log(rst);
                        up7niuKey = rst;
                    }
                });
            }
        },
        getSelfOpts: function ($area){ //获取区域个人配置
            var me = this;
            //按钮cls，从属全局配置
            //个人数据从 data-options 上获得
            var selfOpt =  $area.data('opts');
            if(!selfOpt){
                selfOpt = $.extend(true, {}, me.o.opt, $T.data($area));
                if(me.o.$area.prev(selfOpt.input).length){
                    selfOpt.$field = $area.prev(selfOpt.input); //area 的 prev() 指向用来放值的输入框
                }
                if(!selfOpt.data && selfOpt.$field){
                    var vals = selfOpt.$field.val();
                    if(vals){ //只有有值才赋值
                        selfOpt.data = vals.split(',');
                    }

                }
                selfOpt.data = selfOpt.data || []; // 如果没有值则设为空数组
                console.log('selfOpt:', selfOpt);
                $area.data('opts', selfOpt);
            }
        },
        htmlInit: function ($area){ // 初始化html
            var me = this;
            var opts = $area.data('opts');
            $area.html(`
                <button type="button" class="btn btn-info btn-small ${me.o._btn}">${opts.btnTxt}</button>
                <span class="grey s-uploadTip ${me.o._tip}">${opts.tipTxt}</span>
                <ul class="ul-uploadThumb ${me.o._thumb}"></ul>
                <input class="${me.o._file} hide" type="file" accept="${opts.accept}" ${opts.multiple ? 'multiple': ''} />
            `);
            var $thumb = $area.find('.' + me.o._thumb);
            $thumb.data('field', opts.$field); //把 $field对象绑到$thumb上
            me.updateThumb($thumb, opts.data, 'replace', true); //初始化 thumb 图片
            $thumb.on('click','.s-op-remove',function (){//删除事件
                var $li = $(this).parent('.li-thumb');
               $li.remove();
               $area.find('.' + me.o._file).val('');
               me.updateUploadVals($thumb);
            });
        },
        upload: function ($area){ //上传事件
            var me = this;
            // console.log($area, cs.opt);
            var opts = $area.data('opts');
            var $btn = $area.find('.' + me.o._btn);
            var $file = $area.find('.' + me.o._file);
            var $thumb = $area.find('.' + me.o._thumb);
            $btn .click(function (){
                if(!opts.multiple && $thumb.find('li').length > 0){
                    $pop.msg('只能上传一个文件');
                    return;
                }
                $file.click();
            });

            //算出用来比较的maxsize，以k为单位
            var sizeSet = opts.maxSize.match(/^(\d+)(k|m|K|M)$/);
            if (!sizeSet) {
                $pop.msg('控件最大上传大小设置不正确！');
                return;
            }
            var maxS = sizeSet[1];
            var maxU = sizeSet[2] ? sizeSet[2].toLowerCase() : 'k';
            if (maxU == 'm') {
                maxS = maxS * 1024
            };

            $file.change(function (){
                console.log(this.files);
                var files = [];
                var timeStr = new Date().getTime();
                $.each(this.files, function (i, file){
                    var fileSize = Math.ceil(file.size / 1024);
                    if (fileSize > maxS) {
                        $pop.msg('文件大于' + opts.maxSize + '，无法上传！');
                        return false;
                    }

                    var fileId = timeStr + '_' + i;
                    var fileA = file.name.split('.');
                    var fileType = fileA[fileA.length-1].toLowerCase();
                    files.push({
                        id: fileId,
                        type: fileType,
                        file: file,
                        fileName: file.name,
                        fileKey: me.upload7Opt.key + opts.path + '/' + fileId + '.' + fileType,  // 固定项目文件路径 + 当前分类path + / + fileId + . + 文件后缀名,
                    });
                });
                console.log('fileKey:', files);
                me.updateThumb($thumb, files, 'add');
                //上传
                me.up7Doing($thumb, files);
            });
        },
        up7Doing: function ($thumb, files){ //七牛上传
            var me = this;
            $.each(files, function (i, file){
                console.log(file);
                const observable = qiniu.upload(file.file, file.fileKey, up7niuKey); //文件, key, token
                const subscription = observable.subscribe(function next(res){
                    console.log('next:',  res);
                    var per = res.total.percent.toFixed(1) + '%';
                    $('#per-' + file.id).show();
                    $('#perCur-' + file.id).css({width: per});
                    $('#perTxt-' + file.id).show().html(per);
                },
                function error(err){
                    console.log('error:', err);
                },
                function complete(res){
                    console.log('complete:', res);
                    var imgUrl = me.upload7Opt.baseUrl + res.key;
                    $('#per-' + file.id).hide();
                    $('#perTxt-' + file.id).hide();
                    $('#img-' + file.id).attr({rel: imgUrl});
                    if(file.type == 'mp4'){
                        $('#img-' + file.id).attr({src: imgUrl + '?vframe/jpg/offset/7/w/100/h/100'});
                    }else{
                        $('#img-' + file.id).attr({src: imgUrl + '?imageMogr2/thumbnail/100x100'});
                    }
                    me.updateUploadVals($thumb);
                }); // 上传开始
            });
        },
        updateUploadVals: function ($thumb){ // 更新上传后，更新输入框的值
            var me = this;
            var $field = $thumb.data('field');
            console.log($field);
            if($field){
                var $imgs = $thumb.find('.' + me.o.namespace + me.o.hen + 'itemPic');
                var vals = [];
                $imgs.each(function (i, v){
                    vals.push($(v).attr('rel'));
                });
                console.log(vals);
                $field.val(vals.join(','));
            }
        },
        updateThumb: function ($thumb, list, type, first){ // 更新 预览小图片 type: 'add' | 'replace'
            var me = this;
            var thumbHtml = '';
            // console.log($thumb, list);
            $.each(list,function (i,v){
                var pic = v; //{id: string; fileName: string; type:'jpg'| 'mp4' | 'png', url: string;}
                if( typeof v == 'string'){
                    var info = v.match(/[/]([^/]+)$/);
                    var infoA = info[1].split('.');
                    pic = {id: infoA[0], fileName: info[1], type: infoA[1].toLowerCase(), url: v };
                }

                // console.log(pic);
                let img = me.renderImgItem(pic);
                thumbHtml += `
                <li id="li-_-${pic.id}" rel="${i}" class="li-thumb" rel="${pic.id}">
                  ${img}
                  <span class="s-curPerTxt" id="perTxt-${pic.id}"></span>
                  <span class="s-percent" id="per-${pic.id}"><span id="perCur-${pic.id}" class="s-curPer"></span></span>
                  <span class="s-op-remove icon-trash" title="删除"></span>
                  <span class="s-isVideo icon-facetime_video" ${pic.type== 'mp4' ? 'style="display: block"': ''} title="视频"></span>
                </li>`;
            });
            $thumb[type=='add'?'append':'html'](thumbHtml);
            if(first){me.updateDragSort($thumb);}
        },
        renderImgItem: function (data){//渲染预览图片 {id: string; fileName: string; type:'jpg'| 'mp4' | 'png', url: string;}
            var me = this;
            const fileType = data.type;
            var imgUrl = data.url? data.url : base + '/static/images/icon/file-'+ fileType +'.png';
            if(thumbTypeIcons.includes(fileType)){//thumbTypeIcons 类型，暂时只有pdf,mp4
                return `<img id="img-${data.id}" class="${me.o.namespace}${me.o.hen}itemPic img-${fileType}" src="${imgUrl}?vframe/jpg/offset/7/w/100/h/100" rel="${imgUrl}">`;
            }else{ //else 暂不不细区分,归为图片类型
                return `<img id="img-${data.id}" class="${me.o.namespace}${me.o.hen}itemPic img-pic" src="${imgUrl}?imageMogr2/thumbnail/80x80" rel="${imgUrl}">`;
            }
        },
        updateDragSort: function ($thumb){ //拖动绑定
            var me = this;
            //ul-uploadThumb
            // o.zoomView && $thumbUl.viewer('update');
            // console.log('updateDragSort:', $thumb);
            // $thumb.dragsort('destroy');
            $thumb.dragsort({
                dragSelector: "li",
                dragBetween: false,
                dragSelectorExclude: '.s-op-remove',
                placeHolderTemplate: '<li class="li-thumb"></li>', //拖动是阴影
                dragEnd: function () {
                    var _self = $(this), _p = _self.parent();
                    me.updateUploadVals($thumb);
                    // console.log(_self, $T.data(_self));
                }
            });
        }


    };

    return back;

});